<!DOCTYPE html>
<html lang="zh-CN" th:replace="~{layout :: layout(~{::title}, ~{::main}, ~{::script})}">
<head>
    <title th:text="${site.title ?: '机械设备制造商'} + ' - 产品展示'">机械设备制造商 - 产品展示</title>
</head>
<body>
    <main>
        <!-- 面包屑导航 -->
        <section class="breadcrumb-section">
            <div class="container">
                <nav class="breadcrumb-nav">
                    <a href="/" class="breadcrumb-item">首页</a>
                    <span class="breadcrumb-separator">></span>
                    <span class="breadcrumb-item current" id="current-category">产品展示</span>
                </nav>
            </div>
        </section>

        <!-- 产品展示主体 -->
        <section class="products-main">
            <div class="container">
                <div class="products-layout">
                    <!-- 左侧筛选栏 -->
                    <aside class="products-sidebar">
                        <div class="sidebar-section">
                            <h3 class="sidebar-title">产品分类</h3>
                            <div class="category-filters" id="category-filters">
                                <div class="loading-placeholder">
                                    <div class="loading-spinner"></div>
                                    <p>加载分类中...</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="sidebar-section">
                            <h3 class="sidebar-title">价格区间</h3>
                            <div class="price-filters">
                                <div class="price-range">
                                    <label class="filter-checkbox">
                                        <input type="radio" name="price" value="">
                                        <span>全部价格</span>
                                    </label>
                                    <label class="filter-checkbox">
                                        <input type="radio" name="price" value="0-1000">
                                        <span>¥0 - ¥1,000</span>
                                    </label>
                                    <label class="filter-checkbox">
                                        <input type="radio" name="price" value="1000-5000">
                                        <span>¥1,000 - ¥5,000</span>
                                    </label>
                                    <label class="filter-checkbox">
                                        <input type="radio" name="price" value="5000-10000">
                                        <span>¥5,000 - ¥10,000</span>
                                    </label>
                                    <label class="filter-checkbox">
                                        <input type="radio" name="price" value="10000+">
                                        <span>¥10,000以上</span>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="sidebar-section">
                            <h3 class="sidebar-title">联系我们</h3>
                            <div class="contact-info">
                                <div class="contact-item">
                                    <i class="fas fa-phone"></i>
                                    <span>+86-512-12345678</span>
                                </div>
                                <div class="contact-item">
                                    <i class="fas fa-envelope"></i>
                                    <span>sales@example.com</span>
                                </div>
                                <div class="contact-item">
                                    <i class="fas fa-map-marker-alt"></i>
                                    <span>江苏省苏州市工业园区</span>
                                </div>
                            </div>
                            <a href="/contact" class="btn btn-primary btn-full">立即询价</a>
                        </div>
                    </aside>

                    <!-- 右侧产品列表 -->
                    <div class="products-content">
                        <!-- 产品列表头部 -->
                        <div class="products-header">
                            <div class="products-info">
                                <h1 class="products-title" id="products-title">全部产品</h1>
                                <p class="products-count" id="products-count">共找到 <span id="total-count">0</span> 个产品</p>
                            </div>
                            <div class="products-actions">
                                <div class="sort-options">
                                    <label>排序方式：</label>
                                    <select id="sort-select" class="sort-select">
                                        <option value="priority,desc">按优先级</option>
                                        <option value="creationTimestamp,desc">最新发布</option>
                                        <option value="displayName,asc">名称排序</option>
                                    </select>
                                </div>
                                <div class="view-options">
                                    <button class="view-btn active" data-view="grid">
                                        <i class="fas fa-th"></i>
                                    </button>
                                    <button class="view-btn" data-view="list">
                                        <i class="fas fa-list"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 产品网格 -->
                        <div class="products-grid" id="products-grid">
                            <div class="loading-placeholder">
                                <div class="loading-spinner"></div>
                                <p>正在加载产品...</p>
                            </div>
                        </div>

                        <!-- 分页导航 -->
                        <div class="pagination-wrapper" id="pagination-wrapper">
                            <!-- 分页控件将通过JavaScript动态生成 -->
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 12;
        let currentCategory = '';
        let currentSort = 'priority,desc';
        let currentView = 'grid';
        let allProducts = [];
        let filteredProducts = [];

        document.addEventListener('DOMContentLoaded', function() {
            // 从URL参数获取分类，支持多种参数格式
            const urlParams = new URLSearchParams(window.location.search);
            currentCategory = urlParams.get('productTypeRef') || urlParams.get('category') || '';
            
            console.log('Initial category from URL:', currentCategory);
            
            // 加载数据
            loadProductTypes();
            loadProducts();
            
            // 绑定事件
            bindEvents();
        });

        // 绑定事件监听器
        function bindEvents() {
            // 排序选择
            document.getElementById('sort-select').addEventListener('change', function() {
                currentSort = this.value;
                currentPage = 1;
                loadProducts();
            });

            // 视图切换
            document.querySelectorAll('.view-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    currentView = this.dataset.view;
                    renderProducts(filteredProducts);
                });
            });

            // 价格筛选
            document.querySelectorAll('input[name="price"]').forEach(input => {
                input.addEventListener('change', function() {
                    filterProducts();
                });
            });
        }

        // 加载产品类型
        async function loadProductTypes() {
            try {
                const response = await fetch('/apis/content.halo.run/v1alpha1/product-types');
                if (!response.ok) throw new Error('Failed to load product types');
                
                const data = await response.json();
                renderCategories(data.items || []);
            } catch (error) {
                console.error('加载产品类型失败:', error);
                renderFallbackCategories();
            }
        }

        // 渲染分类筛选
        function renderCategories(productTypes) {
            const container = document.getElementById('category-filters');
            container.innerHTML = '';

            // 全部分类选项
            const allOption = document.createElement('label');
            allOption.className = 'filter-checkbox';
            allOption.innerHTML = `
                <input type="radio" name="category" value="" ${!currentCategory ? 'checked' : ''}>
                <span>全部分类</span>
            `;
            container.appendChild(allOption);

            // 各个分类选项
            productTypes.forEach(type => {
                const spec = type.spec || type;
                const status = type.status || {};
                const displayName = spec.displayName || '未命名分类';
                const productCount = status.productCount || 0;
                
                const option = document.createElement('label');
                option.className = 'filter-checkbox';
                option.innerHTML = `
                    <input type="radio" name="category" value="${type.metadata?.name || ''}" 
                           ${currentCategory === (type.metadata?.name || '') ? 'checked' : ''}>
                    <span>${displayName} (${productCount})</span>
                `;
                container.appendChild(option);
            });

            // 绑定分类筛选事件
            document.querySelectorAll('input[name="category"]').forEach(input => {
                input.addEventListener('change', function() {
                    currentCategory = this.value;
                    currentPage = 1;
                    updateBreadcrumb();
                    updateUrlParams();
                    loadProducts();
                });
            });
        }

        // 加载产品数据
        async function loadProducts() {
            try {
                // 显示加载状态
                showLoadingState();
                
                // 构建API URL，使用正确的Halo API端点
                let apiUrl = '/apis/content.halo.run/v1alpha1/products?page=1&size=100';
                if (currentCategory) {
                    apiUrl += `&productTypeRef=${encodeURIComponent(currentCategory)}`;
                }
                
                console.log('Loading products from:', apiUrl);
                
                const response = await fetch(apiUrl);
                if (!response.ok) throw new Error(`HTTP ${response.status}: Failed to load products`);
                
                const data = await response.json();
                allProducts = data.items || [];
                console.log(`Loaded ${allProducts.length} products for category:`, currentCategory);
                
                filterProducts();
                updateProductsInfo();
                hideLoadingState();
            } catch (error) {
                console.error('加载产品失败:', error);
                renderFallbackProducts();
                hideLoadingState();
            }
        }

        // 筛选产品
        function filterProducts() {
            filteredProducts = [...allProducts];

            // 价格筛选
            const selectedPrice = document.querySelector('input[name="price"]:checked')?.value;
            if (selectedPrice) {
                filteredProducts = filteredProducts.filter(product => {
                    const price = product.spec?.price || 0;
                    if (selectedPrice === '0-1000') return price <= 1000;
                    if (selectedPrice === '1000-5000') return price > 1000 && price <= 5000;
                    if (selectedPrice === '5000-10000') return price > 5000 && price <= 10000;
                    if (selectedPrice === '10000+') return price > 10000;
                    return true;
                });
            }

            renderProducts(filteredProducts);
        }

        // 渲染产品列表
        function renderProducts(products) {
            const grid = document.getElementById('products-grid');
            grid.innerHTML = '';
            grid.className = `products-grid ${currentView}-view`;

            if (products.length === 0) {
                grid.innerHTML = `
                    <div class="no-products">
                        <i class="fas fa-box-open"></i>
                        <h3>暂无产品</h3>
                        <p>当前筛选条件下没有找到相关产品</p>
                    </div>
                `;
                return;
            }

            products.forEach(product => {
                const card = createProductCard(product);
                grid.appendChild(card);
            });

            // 触发动画
            setTimeout(() => {
                animateProductCards();
            }, 100);
        }

        // 创建产品卡片
        function createProductCard(product) {
            const spec = product.spec || {};
            const status = product.status || {};
            const metadata = product.metadata || {};
            
            // 适配Product数据结构
            const displayName = spec.displayName || metadata.name || '未命名产品';
            const description = spec.description || '优质产品，欢迎咨询';
            const images = spec.images || [];
            const price = spec.price || 0;
            const samplePrice = spec.samplePrice || 0;
            const minOrderQuantity = spec.minOrderQuantity || 1;
            
            // 调试日志：打印产品和图片信息
            console.log('Product:', displayName, 'Images:', images);
            
            const firstImage = images.length > 0 
                ? getImageUrl(images[0])
                : getPlaceholderImage(displayName);
            
            console.log('Final image URL:', firstImage);

            const card = document.createElement('div');
            card.className = 'product-card';
            
            card.innerHTML = `
                <div class="product-image">
                    <img src="${firstImage}" alt="${displayName}" loading="lazy" 
                         onerror="this.src='${getPlaceholderImage(displayName)}'; console.log('Image load failed for: ${firstImage}');">
                    <div class="product-badges">
                        ${spec.published === false ? '<span class="badge badge-draft">草稿</span>' : ''}
                        ${spec.featured ? '<span class="badge badge-featured">推荐</span>' : ''}
                    </div>
                </div>
                <div class="product-info">
                    <h3 class="product-title">${displayName}</h3>
                    <p class="product-desc">${description}</p>
                    <div class="product-details">
                        ${price > 0 ? `<div class="detail-item"><span>单价：</span><strong>¥${price.toFixed(2)}</strong></div>` : ''}
                        ${samplePrice > 0 ? `<div class="detail-item"><span>样品价：</span><strong>¥${samplePrice.toFixed(2)}</strong></div>` : ''}
                        <div class="detail-item"><span>起订量：</span><strong>${minOrderQuantity}件</strong></div>
                        ${spec.brand ? `<div class="detail-item"><span>品牌：</span><strong>${spec.brand}</strong></div>` : ''}
                    </div>
                    <div class="product-actions">
                        <button class="btn btn-primary" onclick="contactForProduct('${displayName}')">
                            <i class="fas fa-phone"></i> 立即询价
                        </button>
                        <button class="btn btn-outline" onclick="addToFavorites('${metadata.name || ''}')">
                            <i class="far fa-heart"></i> 收藏
                        </button>
                    </div>
                </div>
            `;
            
            return card;
        }

        // 更新产品信息显示
        function updateProductsInfo() {
            const titleEl = document.getElementById('products-title');
            const countEl = document.getElementById('total-count');
            
            if (currentCategory) {
                // 根据分类名称更新标题
                const categoryInput = document.querySelector(`input[name="category"][value="${currentCategory}"]`);
                const categoryName = categoryInput ? categoryInput.nextElementSibling.textContent.split(' (')[0] : '产品分类';
                titleEl.textContent = categoryName;
            } else {
                titleEl.textContent = '全部产品';
            }
            
            // 显示当前筛选条件下的产品数量
            if (filteredProducts && filteredProducts.length !== undefined) {
                countEl.textContent = filteredProducts.length;
            } else {
                countEl.textContent = allProducts ? allProducts.length : 0;
            }
        }

        // 更新面包屑导航
        function updateBreadcrumb() {
            const breadcrumb = document.getElementById('current-category');
            if (currentCategory) {
                const categoryInput = document.querySelector(`input[name="category"][value="${currentCategory}"]`);
                const categoryName = categoryInput ? categoryInput.nextElementSibling.textContent.split(' (')[0] : '产品分类';
                breadcrumb.textContent = categoryName;
            } else {
                breadcrumb.textContent = '产品展示';
            }
        }

        // 获取图片URL
        function getImageUrl(url) {
            if (!url) return '';
            
            console.log('Using image URL directly:', url);
            
            // 直接使用接口返回的URL
            return url;
        }

        // 获取占位图片
        function getPlaceholderImage(productName) {
            return 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=industrial%20machinery%20product%20professional%20blue%20theme&image_size=landscape_4_3';
        }

        // 产品卡片动画
        function animateProductCards() {
            const productCards = document.querySelectorAll('.product-card');
            productCards.forEach((card, index) => {
                card.style.opacity = '0';
                card.style.transform = 'translateY(30px)';
                card.style.transition = 'all 0.6s ease';
                
                setTimeout(() => {
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, index * 100);
            });
        }

        // 渲染备用分类
        function renderFallbackCategories() {
            const fallbackCategories = [
                { metadata: { name: 'cnc-machines' }, spec: { displayName: '数控机床' }, status: { productCount: 15 } },
                { metadata: { name: 'hydraulic-equipment' }, spec: { displayName: '液压设备' }, status: { productCount: 12 } },
                { metadata: { name: 'automation' }, spec: { displayName: '自动化设备' }, status: { productCount: 8 } },
                { metadata: { name: 'molds' }, spec: { displayName: '模具设备' }, status: { productCount: 10 } },
                { metadata: { name: 'laser-cutting' }, spec: { displayName: '激光切割设备' }, status: { productCount: 6 } },
                { metadata: { name: 'welding' }, spec: { displayName: '焊接设备' }, status: { productCount: 9 } }
            ];
            renderCategories(fallbackCategories);
            
            // 显示错误提示
            console.warn('使用备用分类数据，可能无法加载服务器数据');
        }

        // 渲染备用产品
        function renderFallbackProducts() {
            const fallbackProducts = [
                {
                    metadata: { name: 'cnc-machining-center-001' },
                    spec: {
                        displayName: 'VMC850立式加工中心',
                        description: '高精度立式加工中心，适用于各种复杂零件加工',
                        price: 280000,
                        samplePrice: 500,
                        minOrderQuantity: 1,
                        images: []
                    }
                },
                {
                    metadata: { name: 'hydraulic-press-002' },
                    spec: {
                        displayName: '200吨液压机',
                        description: '大型液压压力机，适用于金属成型、压制等工艺',
                        price: 150000,
                        minOrderQuantity: 1,
                        images: []
                    }
                }
            ];
            
            allProducts = fallbackProducts;
            filterProducts();
            updateProductsInfo();
        }

        // 联系询价
        function contactForProduct(productName) {
            // 这里可以跳转到联系页面或弹出询价表单
            window.location.href = `/contact?product=${encodeURIComponent(productName)}`;
        }

        // 添加收藏
        function addToFavorites(productId) {
            // 这里可以实现收藏功能
            alert('收藏功能开发中...');
        }

        // 显示加载状态
        function showLoadingState() {
            const grid = document.getElementById('products-grid');
            grid.innerHTML = `
                <div class="loading-placeholder">
                    <div class="loading-spinner"></div>
                    <p>正在加载产品...</p>
                </div>
            `;
        }

        // 隐藏加载状态
        function hideLoadingState() {
            // 加载状态会在renderProducts中被替换
        }

        // 更新URL参数
        function updateUrlParams() {
            const url = new URL(window.location);
            if (currentCategory) {
                url.searchParams.set('productTypeRef', currentCategory);
                // 删除旧的参数格式以保持URL整洁
                url.searchParams.delete('category');
            } else {
                url.searchParams.delete('productTypeRef');
                url.searchParams.delete('category');
            }
            window.history.replaceState({}, '', url);
        }

        console.log('B2B产品展示页面加载完成！');
    </script>
</body>
</html>